import { Injectable, Inject } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import type { ILanguageService } from '@wwjCommon/language/language.interface';

/**
 * 系统信息服务
 * 基于PHP的SystemService实现
 * 
 * 功能:
 * 1. 系统信息查询
 * 2. 环境检测
 * 3. 缓存管理
 * 4. 队列和计划任务检查
 */
@Injectable()
export class SystemService {
  constructor(
    private readonly configService: ConfigService,
    @Inject('ILanguageService') private readonly languageService: ILanguageService,
  ) {}

  /**
   * 获取版权信息(网站整体，不按照站点设置)
   * 对应PHP: SystemService::getInfo()
   */
  async getInfo() {
    return {
      os: process.platform,
      environment: process.env.NODE_ENV || 'development',
      node_v: process.version,
      version: this.configService.get('app.version', '1.0.0'),
    };
  }

  /**
   * 获取域名配置
   * 对应PHP: SystemService::getUrl()
   */
  async getUrl() {
    // 模拟获取域名配置
    return {
      admin_url: this.configService.get('app.adminUrl', 'http://localhost:3000'),
      api_url: this.configService.get('app.apiUrl', 'http://localhost:3001'),
      web_url: this.configService.get('app.webUrl', 'http://localhost:3002'),
    };
  }

  /**
   * 获取系统信息
   * 对应PHP: SystemService::getSystemInfo()
   */
  async getSystemInfo() {
    const server = [];
    server.push({ 
      name: await this.languageService.getDictData('dict_setting.server_system'), 
      server: process.platform 
    });
    server.push({ 
      name: await this.languageService.getDictData('dict_setting.server_setting'), 
      server: 'Node.js' 
    });
    server.push({ 
      name: await this.languageService.getDictData('dict_setting.php_version'), 
      server: process.version 
    });

    // 环境权限检测
    const systemVariables = [];
    
    // Node.js 版本检测
    const nodeVersion = process.version;
    const nodeVersionOk = this.compareVersion(nodeVersion, '16.0.0') >= 0;
    systemVariables.push({
      name: 'Node.js',
      need: await this.languageService.getDictData('dict_setting.php_authority_ask'),
      status: nodeVersionOk,
    });

    // 内存检测
    const memoryUsage = process.memoryUsage();
    const memoryOk = memoryUsage.heapUsed < memoryUsage.heapTotal * 0.9;
    systemVariables.push({
      name: 'Memory',
      need: await this.languageService.getDictData('dict_setting.php_authority_ask'),
      status: memoryOk,
    });

    // 目录权限检测
    const dirsList = [
      {
        path: process.cwd() + '/runtime',
        need: await this.languageService.getDictData('dict_setting.file_authority_ask'),
        path_name: '/runtime',
        name: 'runtime',
      },
      {
        path: process.cwd() + '/public/upload',
        need: await this.languageService.getDictData('dict_setting.file_authority_ask'),
        path_name: '/public/upload',
        name: 'upload',
      },
    ];

    // 目录可读可写检测
    for (const dir of dirsList) {
      try {
        const fs = require('fs');
        fs.accessSync(dir.path, fs.constants.R_OK | fs.constants.W_OK);
        dir.status = true;
      } catch (error) {
        dir.status = false;
      }
    }

    return {
      server,
      system_variables: systemVariables,
      dirs_list: dirsList,
    };
  }

  /**
   * 清理表缓存
   * 对应PHP: SystemService::schemaCache()
   */
  async schemaCache() {
    // 模拟清理表缓存
    return {
      message: await this.languageService.getApiMessage('cache_clear_success'),
    };
  }

  /**
   * 清理缓存
   * 对应PHP: SystemService::clearCache()
   */
  async clearCache() {
    // 模拟清理缓存
    return {
      message: await this.languageService.getApiMessage('cache_clear_success'),
    };
  }

  /**
   * 校验消息队列是否正常运行
   * 对应PHP: SystemService::checkJob()
   */
  async checkJob() {
    // 模拟队列检查
    return {
      status: true,
      message: await this.languageService.getApiMessage('job_running'),
    };
  }

  /**
   * 校验计划任务是否正常运行
   * 对应PHP: SystemService::checkSchedule()
   */
  async checkSchedule() {
    // 模拟计划任务检查
    return {
      status: true,
      message: await this.languageService.getApiMessage('schedule_running'),
    };
  }

  /**
   * 环境变量查询
   * 对应PHP: SystemService::getEnvInfo()
   */
  async getEnvInfo() {
    return {
      NODE_ENV: process.env.NODE_ENV || 'development',
      PORT: process.env.PORT || '3001',
      DATABASE_URL: process.env.DATABASE_URL ? '***' : 'Not set',
      REDIS_URL: process.env.REDIS_URL ? '***' : 'Not set',
    };
  }

  /**
   * 版本比较
   * @param version1 版本1
   * @param version2 版本2
   * @returns 比较结果
   */
  private compareVersion(version1: string, version2: string): number {
    const v1 = version1.replace(/^v/, '').split('.').map(Number);
    const v2 = version2.replace(/^v/, '').split('.').map(Number);
    
    for (let i = 0; i < Math.max(v1.length, v2.length); i++) {
      const num1 = v1[i] || 0;
      const num2 = v2[i] || 0;
      
      if (num1 > num2) return 1;
      if (num1 < num2) return -1;
    }
    
    return 0;
  }
}